import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from "axios";

class MyRequest {
  instance: AxiosInstance;
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    // 封装拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        return config;
      },
      (err: any) => err
    );
    // 响应拦截器：通过返回状态码鉴权
    this.instance.interceptors.response.use(
      (config) => {
        return config.data;
      },
      (err) => {
        console.log("错误信息:", err.response);
      }
    );
  }
  request<T>(conifg: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(conifg)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }

  post<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }
  put<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "PUT" });
  }
  delete<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }
  uploadFilePost<T>(config: AxiosRequestConfig): Promise<T> {
    config.headers = { "Content-Type": "multipart/form-data" };
    return this.request<T>({ ...config, method: "POST" });
  }
}

export default MyRequest;
